<?php

App::import('Controller', 'Expenses');
App::import('Controller', 'Users');
App::import('Model', 'Expenses');
App::import('Model', 'Expenditure');
App::import('Model', 'Building');
App::import('Model', 'ExpenditureType');
App::import('Model', 'Account');
App::import('Model', 'RefinancingSystem');

class BuildingsController extends AppController {
    var $name = 'Buildings';

	function index() {
		$this->Building->recursive = 0;
	/*	$permit  = $this->Session->read('permit_build');
		if ( $permit!= null ){
			$data = null;
			$new  = null;
			foreach ($permit as $key => $value) {
				$this->paginate = array(
							 'conditions' => array( 'Building.building_id' => $value )
						 );
				$data[$key]  = $this->paginate();
			}
			foreach ( $data as $key1 => $value1)
			{
				$new[$key1] = $value1[0];
			}
			$this->set('buildings', $new);
		}else{
			  $this->Session->setFlash(__('You have nothing assigned', true));
			  $this->redirect(array('controller' => 'users', 'action' => 'welcome'));
		}*/
		$this->set('buildings', $this->paginate());
	}

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid building', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('building', $this->Building->read(null, $id));
    }

    function add() {
        if (!empty($this->data)) {
            $this->Building->create();
            $this->data['Building']['end_date'] = null;
            if ($this->Building->save($this->data)) {
                $this->Session->setFlash(__('The building has been saved', true));
                $sql = "SELECT max(building_id) id
                        FROM   buildings";
                $new_id = $this->Building->query($sql);
                // Insersion default
                $payment_due = new PaymentDue();
                $payment_due_data = array();
                $payment_due_data["payment_due_id"] = null;
                $payment_due_data["building_id"] = $new_id['0']['0']['id'];
                $payment_due_data["first_due_date"] = 8;
                $payment_due_data["second_due_date"] = 15;
                $payment_due_data["second_due_rate"] = 0.005;
                $payment_due_data["interest_scheme"] = 31;
                $payment_due_data["annual_rate"] = 0.12;
                $payment_due->save($payment_due_data);
                // Insersion default
                $refinancing_system = new RefinancingSystem();
                $refinancing_system_data = array();
                $refinancing_system_data["refinancing_system_id"] = null;
                $refinancing_system_data["building_id"] = $new_id['0']['0']['id'];
                $refinancing_system_data["amortization_system"] = 15;
                $refinancing_system_data["annual_rate"] = 0.2;
                $refinancing_system->save($refinancing_system_data);

				$sql = "SELECT building_id
                        FROM   buildings 
                        order by building_id desc";
                $ids = $this->Building->query($sql);
                $building_id  = $ids[0]["buildings"]["building_id"];
				$user = new UsersController;
                $user->constructClasses();
                $user->add_build($building_id);
				$this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The building could not be saved. Please, try again.', true));
            }
        }
        $aptBussinesses = $this->Building->BuildingAptBussiness->find('list',
                array('conditions' => array('BuildingAptBussiness.lookup_type' => 'APT_BUSINESS')));
        $buildingDoormen = $this->Building->BuildingDoorman->find('list');
        $addresses = $this->Building->Address->find('list');
        $buildingExpenseLiquidationTypes = $this->Building->BuildingExpenseLiquidationType->find('list',
                array('conditions' => array('BuildingExpenseLiquidationType.lookup_type' => 'EXPENSE_LIQUIDATION_TYPE')));
        $customers = $this->Building->Customer->find('list');
        $this->set(compact('aptBussinesses','buildingDoormen', 'addresses', 'buildingExpenseLiquidationTypes','customers'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid building', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->Building->save($this->data)) {
                $this->Session->setFlash(__('The building has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The building could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Building->read(null, $id);
        }
        $aptBussinesses = $this->Building->BuildingAptBussiness->find('list',
                array('conditions' => array('BuildingAptBussiness.lookup_type' => 'APT_BUSINESS')));
        $buildingDoormen = $this->Building->BuildingDoorman->find('list');
        $addresses = $this->Building->Address->find('list');
        $buildingExpenseLiquidationTypes = $this->Building->BuildingExpenseLiquidationType->find('list',
                array('conditions' => array('BuildingExpenseLiquidationType.lookup_type' => 'EXPENSE_LIQUIDATION_TYPE')));
        $customers = $this->Building->Customer->find('list');
        $this->set(compact('aptBussinesses','buildingDoormen', 'addresses', 'buildingExpenseLiquidationTypes','customers'));
    }

	function getTotalFondoOrd($id)
	{
		$this->data = $this->Building->read(null, $id);
		var_dump($this->data);
		die();
	}

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for building', true));
            $this->redirect(array('action'=>'index'));
        }
        if (empty($this->data)) {
            $this->data = $this->Building->read(null, $id);
        }
        if (!empty($this->data)) {
            // ACA SETEO EL UPDATED_BY
            $this->data['Building']['end_date'] = date('Y-m-d H:i:s');
            if ($this->Building->save($this->data)) {
                $this->Session->setFlash(__('Building deleted', true));
            } else {
                $this->Session->setFlash(__('Building was not deleted', true));
            }
        }
        $this->redirect(array('action' => 'index'));
    }

    function print_expenditures_resume($id = null) {
      
      $building=new Building;
      $building_data=$building->find('first',array('conditions' => array('Building.building_id' => $id)));
//var_dump($building_data["Building"]);
      $expen=new Expenditure;
      $expen_data=$expen->find('all', array('conditions' => array('Expenditure.building_id' => $id)));

      $expenType=new ExpenditureType;
      $expenType_data=$expenType->find('all');
      $expenditureTypeArray= Array();
      $expenditureTypeSourceArray= Array();

      foreach($expenType_data as $unExpType){
      
      $expenditureTypeArray[$unExpType["ExpenditureType"]['expenditure_type_id']]=$unExpType["ExpenditureType"]['description'];
      $expenditureTypeSourceArray[$unExpType["ExpenditureType"]['expenditure_type_id']]=$unExpType["ExpenditureType"]['expenditure_type_source'];
      }

      $this->set('building',$building_data);
      $this->set('expenditures',$expen_data);
      $this->set('expenditureTypeArray',$expenditureTypeArray);
      $this->set('expenditureTypeSourceArray',$expenditureTypeSourceArray);
	  $filetmp = '../tmp/resumen/expendituresResume-id'.$id.'-'.date('m').'-'.date('Y').'.pdf';
		
	  $this->set('filetmp',$filetmp);
	  $this->render('print_expenditures_resume');

      $this->Session->setFlash(__('Generated summary', true));
	  $this->redirect(array('action' => 'index'));
		return ($filetmp);
    }

    function process_month_expenses($id = null) {
        // Chequeo si ya proceso la expensa para ese mes
		$dupli = $this->verify_months($id);
		if (!$dupli){
                $this->Session->setFlash(__('The building has already been processed', true));
                $this->redirect(array('action' => 'index'));
        } else if (!$id) {
                $this->Session->setFlash(__('Invalid id for building', true));
                $this->redirect(array('action'=>'index'));
        } else{
            if (empty($this->data)) {
                    $this->data = $this->Building->read(null, $id);
            }
            if (!empty($this->data)) {

                    if ($this->Building->process_month_expenses($this->data)) {
						// LLamamos a la funcion para mandar expensas
						$this->send_expenses($id);
						$this->Session->setFlash(__('Month processed', true));
                    } else {
                            $this->Session->setFlash(__('Month was not processed', true));
                    }
            } else {
                    $this->Session->setFlash(__('Invalid id for building', true));
            }
            $this->redirect(array('action' => 'index'));
        }
    }

	// Verifica si se proceso la expensa para ese mes
	function verify_months($id)
	{
		$sql = "select distinct(e.created)
                        from expenses e, properties p
                        where p.property_id = e.property_id
                        and   p.building_id = $id
                        order by e.created desc;";
		
		$data  = $this->Building->query($sql);
                if ( count($data) == 0)
                    return true;
                $date  = $data[0]["e"]["created"];
		$month = substr($date,5,2);
		$year  = substr($date,0,4);
		
		$month_current = date("m");
		$year_current  = date("Y");

		if ( $year_current > $year )
			return true;
		else if (( $year_current == $year ) && ( $month_current > $month ))
			return true;
 		return false;
	}


	function _create_report($expense)
	{
		$filereport = '/tmp/data/liquidacion.pdf';
		
		if ($expense == null) {
			$this->Session->setFlash('Sorry, there was no PDF selected.');
			$this->redirect(array('action'=>'index'), null, true);
		}
				
		// Otherwise we cannot use this method while developing 
		Configure::write('debug',3);
  
		$responsible = $expense->getResponsible();
		
		$nameOccupant = $responsible["Person"]["surname"]. ', '.$responsible["Person"]["first_name"];
		$typeExpense = $expense["Expense"]["expenditure_type_source"];
		$dateExpense = $expense["Expense"]["created"];
		$debtAmount = $expense["Expense"]["previous_debt"];
		$interests = $expense["Expense"]["interests"];
		$expenseAmount = $expense["Expense"]["amount"];
		$total = $debtAmount + $interests + $expenseAmount;
		
		if ($typeExpense = '6') // SPECIAL
		{
			$typeExpense = 'Extraordinarias';
		}
		else 
		{
			$typeExpense = 'Ordinarias';
		}
		
        $this->set(compact('nameOccupant','dateExpense','debtAmount','interests','expenseAmount','total'));
        $this->set('typeExpense',$typeExpense);
        $this->set('filereport',$filereport);
		
		$this->layout = 'pdf'; //this will use the pdf.ctp layout
		$this->render('report');
		
		return $filereport;
	}

	function _delete_report($report)
	{
		
	}
	
	function _notify_liquidation($expense)
	{			
		$expen = new ExpensesController;
		$expen->constructClasses();
		$fileReport = $expen->report($expense);
		$property_id = $expen->get_property_id($expense);
		$name = $expen->get_name_people($property_id);
		// Obtengo el responsable de la expensa.
		//$mail = $expen->get_mail_people($property_id);
		$mail = "freedy8601@gmail.com";
		// Envio el email al responsable.
		$wasSent = $this->_send_mail("Liquidación de expensas",$mail, $fileReport,$name);
//		$this->_delete_report($fileReport);
	} 
	
    // me pasan el id del edificio.
	function send_expenses($id)
	{
		$building = $this->Building->read(null,$id);				
		$properties = $building["Property"];
		foreach($properties as $property)
		{
			$expenses=new Expense;
			$property_id =   $property["property_id"];
			$month_current = date("m");
			$year_current  = date("Y");  
			$sql = "select * 
					from expenses Expense
					where Expense.property_id =   $property_id 
					and   YEAR(created)  = $year_current
					and   MONTH(created) = $month_current";
			$expenses_data=$expenses->query($sql);
			//find('all', array('conditions' => array('Expense.property_id' => $property["property_id"])));
			foreach($expenses_data as $key => $exp)
			{
				$this->_notify_liquidation($exp["Expense"]["expense_id"]);
			}
		}
		$this->Session->setFlash(__('Process Complete', true));
        $this->redirect(array('action' => 'index'));
	}
	
    function _send_mail($subject,$mail,$file,$name) {

	    $this->Email->to = '<'.$mail.'>';
	    $this->Email->subject = $subject;	    
	    $this->Email->from = '<no-reply@admindeconsorcios.com.ar>';
	    $this->Email->template = 'simple_message'; // note no '.ctp'
	    //Send as 'html', 'text' or 'both' (default is 'text')
	    $this->Email->sendAs = 'both'; // because we like to send pretty mail
	    /* SMTP Options */
	    /* SMTP Options */
	    $this->Email->smtpOptions = array(
	        'port'=>'587',
	        'timeout'=>'30',
	        'host' => 'mail.admindeconsorcios.com.ar',
	        'username'=>'no-reply@admindeconsorcios.com.ar',
	        'password'=>'qwerty'	        
	    );	    
	        
	    /* Set delivery method */
    	$this->Email->delivery = 'smtp';
    	
    	$this->Email->attachments = array(TMP . $file);
		
		$this->set('name',$name);
		
		//Do not pass any args to send()
	    $this->Email->send();
		/* Check for SMTP errors. */
    	$this->set('smtp-errors', $this->Email->smtpError);
	 }
	 
	 function refinance()
	 {
//	 	$buildings = $this->Building->find('list');
//	 	var_dump($buildings);
//	 	die();
	 	
        $this->set('buildings', $this->paginate());
	 }
    
}
?>
